import { ref } from 'vue'
import { useInvestStore } from '@/stores/invest'
import { useLhcStore } from '@/stores/tpl-lhc'

export function useCommonLogic(props) {
  const selectedList = ref([])
  const currentPlayTypeIndex = ref(0)
  const investStore = useInvestStore()
  const lhcStore = useLhcStore()
  const init = () => {
    selectedList.value = []
    notifyParentInvestList([])
  }

  const selectPlayType = (index) => {
    currentPlayTypeIndex.value = index
    lhcStore.setSonGameTypeIndex(index)
    init()
  }

  const notifyParentInvestList = (list) => {
    investStore.setInvestNum(list)
  }

  const fillLastNumber = () => {
    const { lastInvestList } = investStore
    selectedList.value = lastInvestList
    notifyParentInvestList(lastInvestList)
  }

  const updateInvestList = (type, data) => {
    if (type === 'clear') {
      init()
      return
    }

    if (type === 'del') {
      if (selectedList.value.length > 1) {
        const index = selectedList.value[currentPlayTypeIndex.value].findIndex(
          (item) => item.playCode === data.playCode,
        )
        selectedList.value[currentPlayTypeIndex.value].splice(index, 1)
      } else {
        const index = selectedList.value.findIndex((item) => item['playCode'] === data.playCode)
        selectedList.value.splice(index, 1)
      }
    }
  }
  const getParams = () => {
    const { lotteryCode, playTypeCode } = props.renderData
    return selectedList.value.map(({ sonPlayTypeCode, playCode, betAmount }) => ({
      betContent: playCode,
      lotteryCode,
      playTypeCode,
      sonPlayTypeCode,
      playCode,
      betAmount,
    }))
  }
  return {
    selectedList,
    currentPlayTypeIndex,
    init,
    selectPlayType,
    notifyParentInvestList,
    fillLastNumber,
    updateInvestList,
    getParams,
  }
}
